const multiparty = require('multiparty');
const config = require('../../config');
const fs = require('fs');
const path = require('path');
const uploadDir = path.resolve(__dirname, '../../', 'static/img');
const uploadDirBig = path.resolve(__dirname, '../../', 'static/files');

// 文件上传中间件
exports.multiparty_upload = (req, auto) => {
	typeof auto !== "boolean" ? auto = false : null;
	// let multiparty_config = {
	// 	maxFieldsSize: 10 * 1024 * 1024 * 1024,
	// };
	// if (auto) multiparty_config.uploadDir = `${config.HOST}:${config.PORT}/img`;
	return new Promise(async (resovlve, reject) => {
		let form = new multiparty.Form();
		form.uploadDir = `static/img`;
			form.parse(req, (err, fields, files) => {
			if (err) {
				reject(err);
				return
			}
			resovlve({
				fields,
				files
			})
		})
	})
}

// 创建文件并写入到指定的目录 & 返回客户端结果
exports.writeFile = (res, path, file, filename, stream) => {
	return new Promise((resolve, reject) => {
		if (stream) {
			try {
				let readStream = fs.createReadStream(file.path),
					writeStream = fs.createWriteStream(path);
				readStream.pipe(writeStream);
				readStream.on('end', () => {
					resolve();
					fs.unlinkSync(file.path);
					res.send({
						code: 0,
						codeText: 'upload success',
						originalFilename: filename,
						servicePath: path.replace(__dirname, `${config.HOST}:${config.PORT}`)
					});
				});
			} catch (err) {
				reject(err);
				res.send({
					code: 1,
					codeText: err
				});
			}
			return;
		}
		fs.writeFile(path, file, err => {
			if (err) {
				reject(err);
				res.send({
					code: 1,
					codeText: err
				});
				return;
			}
			resolve();
			res.send({
				code: 0,
				codeText: 'upload success',
				originalFilename: filename,
				servicePath: path.replace(__dirname, `${config.HOST}:${config.PORT}`)
			});
		});
	});
};

// 大文件切片上传 & 合并切片
exports.merge = (HASH, count) => {
	return new Promise(async (resolve, reject) => {
		let path = `${uploadDirBig}/${HASH}`,
			fileList = [],
			suffix,
			isExists;
		const exists = function exists(path) {
		    return new Promise(resolve => {
		        fs.access(path, fs.constants.F_OK, err => {
		            if (err) {
		                resolve(false);
		                return;
		            }
		            resolve(true);
		        });
		    });
		};
		isExists = await exists(path);
		if (!isExists) {
			reject('HASH path is not found!');
			return;
		}
		fileList = fs.readdirSync(path);
		if (fileList.length < count) {
			reject('the slice has not been uploaded!');
			return;
		}
		fileList.sort((a, b) => {
			let reg = /_(\d+)/;
			return reg.exec(a)[1] - reg.exec(b)[1];
		}).forEach(item => {
			!suffix ? suffix = /\.([0-9a-zA-Z]+)$/.exec(item)[1] : null;
			fs.appendFileSync(`${uploadDirBig}/${HASH}.${suffix}`, fs.readFileSync(
				`${path}/${item}`));
			fs.unlinkSync(`${path}/${item}`);
		});
		fs.rmdirSync(path);
		resolve({
			path: `/files/${HASH}.${suffix}`,
			filename: `${HASH}.${suffix}`
		});
	});
};

// 检测文件是否存在
exports.exists = (path) => {
    return new Promise(resolve => {
        fs.access(path, fs.constants.F_OK, err => {
            if (err) {
                resolve(false);
                return;
            }
            resolve(true);
        });
    });
};